package cn.sxt.clinic.shiro;

import cn.sxt.clinic.pojo.Doctor;
import cn.sxt.clinic.service.IDoctorService;
import cn.sxt.clinic.service.IPermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/*自定义realm*/
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private IPermissionService permissionService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取认证的信息
        Doctor doctor= (Doctor) principalCollection.getPrimaryPrincipal();
        //查询当前角色拥有的权限表达式
        List<String> jobExpressions = permissionService.getJobExpressions(doctor.getJobName());

        //创建授权信息对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将授权对象的权限表达式个职务信息添加到授权信息对象中
        simpleAuthorizationInfo.addRole(doctor.getJobName());
        simpleAuthorizationInfo.addStringPermissions(jobExpressions);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

        QueryWrapper<Doctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Doctor doctor = doctorService.getOne(queryWrapper);

        if (doctor == null){
            return null;
        }

        //获取密码
        String password = doctor.getPassword();

        //获取盐
        String salt = doctor.getSalt();

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(doctor, password, ByteSource.Util.bytes(salt), this.getName());

        return simpleAuthenticationInfo;
    }
}
